package net.cyue.homework.student.management.util;

import net.cyue.homework.student.management.http.WebResult;
import net.cyue.nest.nestjava.common.enums.HTTPStatus;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPRequest;
import net.cyue.nest.nestjava.common.interfaces.http.IHTTPResponse;

import java.io.IOException;
import java.util.Map;

public class RequestUtil {
    public static <T> T validateData(
        IHTTPRequest request,
        IHTTPResponse response,
        Class<T> clz
    ) throws IOException {
        try {
            T instance = request.body().toObject(clz);
            Map<String, Object> errorMap = DataValidator.validate(instance);
            if (errorMap != null) {
                response.code(HTTPStatus.BAD_REQUEST);
                response.send(errorMap);
                return null;
            }
            return instance;
        } catch (IOException e) {
            response.code(HTTPStatus.BAD_REQUEST);
            response.send(WebResult.failed("错误的参数"));
            return null;
        }
    }
}

